/**
 * 拦截器
 * author: Wanghui <wangh@ciqtek.com>
 * company: ubiot.cn
 * date: 2019-08-10
 */

import { VueRouter } from "vue-router/types/router"
import { getToken } from "@/common/utils"
import store from "@/store"
import {PAGE_LOADING} from "@/store/mutation-types"

// 登陆页面路由 name
const LOGIN_PAGE_NAME = 'login'

/**
 * 路由拦截
 * @param {VueRouter} router
 */
export const intercept = (router: VueRouter) => {
  // 跳转之前
  router.beforeEach((to, from, next) => {
    const token = getToken()
    // 动画效果
    store.commit(PAGE_LOADING, true)
    if (!token && to.name !== LOGIN_PAGE_NAME) {
      // 未登录且要跳转的页面不是登录页
      next({
        name: LOGIN_PAGE_NAME // 跳转到登录页
      })
    }
    else if (!token && to.name === LOGIN_PAGE_NAME) {
      // 未登陆且要跳转的页面是登录页
      next() // 跳转
    }
    else if (token && to.name === LOGIN_PAGE_NAME) {
      // 已登录且要跳转的页面是登录页
      next({
        // 跳转到 home 页
        name: 'home'
      })
    }
    else {
      if (token) {
        // 跳转
        next()
      }
      else {
        next({
          name: LOGIN_PAGE_NAME
        })
      }
    }
  })


  // 跳转之后
  router.afterEach(to => {
    /**
     * 动画效果
     * 模拟加载
     */
    setTimeout(() => store.commit(PAGE_LOADING, false), 300)
  })
}
